/**
 * 利用覆盖层高亮搜索到的文本
 * @param {string|HTMLInputElement} search
 * @param {HTMLElement} targetElement
 */
function overlay(search, targetElement) {
  if (typeof search === "string") {
    search = document.querySelector(search);
  }
  if (!(search instanceof HTMLInputElement)) {
    throw new TypeError("search must be an input element");
  }
  if (!(targetElement instanceof HTMLElement)) {
    throw new TypeError("targetElement must be an HTMLElement");
  }
  search.addEventListener("input", function () {
    const text = targetElement.textContent;

    [].slice
      .call(document.querySelectorAll(".overlay"))
      .forEach((el) => el.remove());

    const value = this.value.trim();
    const length = value.length;
    if (!length) return;

    const arrMatchs = text.split(value);
    if (arrMatchs.length > 1) {
      let start = 0;
      arrMatchs.forEach((parts, index) => {
        if (index == arrMatchs.length - 1) return;
        const range = document.createRange();
        start += parts.length;
        range.setStart(targetElement.firstChild, start);
        range.setEnd(targetElement.firstChild, start + length);

        const bound = range.getBoundingClientRect();
        const elOverlay = document.createElement("ui-overlay");
        elOverlay.className = "overlay";
        document.body.appendChild(elOverlay);

        elOverlay.style.left = `${bound.left}px`;
        elOverlay.style.top = `${bound.top + window.scrollY}px`;
        elOverlay.style.width = `${bound.width}px`;
        elOverlay.style.height = `${bound.height}px`;

        start += length;
      });
    }
  });
}

// css
// ui-overlay {
//   position: absolute;
//   background:red;
//   mix-blend-mode: overlay;
//   z-index: 9;
// }
